<script setup lang="ts">
import { Delete, Edit } from "@element-plus/icons-vue";
import { useBrandStore } from '@/store/brandStore.ts'
import { BatchDeleteBrand, deleteBrand, getBrandCategory, getBrandRegion } from "@/api/brand";
import { brandDate } from "@/api/brand/type";
import { onBeforeMount } from "vue";
import { ElNotification, ElTable } from "element-plus";
import AddBrand from "./brandpopups/AddBrand.vue";
import { useLoginStore } from "@/store/usersLoginStore.ts";
import EditBrand from "./brandpopups/EditBrand.vue";


const loginStore = useLoginStore()

const tableRef = ref<typeof ElTable | null>(null);
const brandStore = useBrandStore();
const requestRegion = ref(false)

const pagination = async (currentPage: number, pageSize: number) => {
  brandStore.reqFrom.page = currentPage
  brandStore.reqFrom.pageSize = pageSize
  try {
    await brandStore.getBrandListFunc()
  } catch (e: any) {
    ElNotification({
      message: e,
      type: 'error',
    })
  }

}
const getRegionFunc = async () => {
  if (brandStore.regionOptions.length === 0) {
    requestRegion.value = true
    const res = await getBrandRegion()
    if (res.code === 200) {
      requestRegion.value = false
      brandStore.regionOptions.push(...res.data.map(name => ({ name })))
    } else {
      requestRegion.value = false
      console.log(res.msg)
    }
  }
}
const getCategoryFunc = async () => {
  if (brandStore.categoryOptions.length === 0) {
    const res = await getBrandCategory()
    if (res.code === 200) {
      brandStore.categoryOptions.push(...res.data.map(name => ({ name })))

    } else {
      console.log(res.msg)
    }
  }
}
const queryBrand = async () => {
  try {
    await brandStore.getBrandListFunc()
  } catch (e: any) {
    ElNotification({
      message: e,
      type: 'error',
    })
  }
}
const edit = async (row: brandDate) => {
  brandStore.editBrand = true
  brandStore.editBrandData.ID = row.ID
  brandStore.editBrandData.name = row.name
  brandStore.editBrandData.description = row.description
  brandStore.editBrandData.logo = row.logo
  brandStore.editBrandData.region = row.region.name
  brandStore.editBrandData.category = row.category.name
  brandStore.editBrandData.status = row.status
}
const del = async (row: brandDate) => {
  const res = await deleteBrand(row.ID)
  if (res.code === 200) {
    await brandStore.getBrandListFunc()
    ElNotification({
      message: '删除成功',
      type: 'success',
    })
  } else {
    ElNotification({
      message: res.msg,
      type: 'error',
    })
  }
}


onBeforeMount(async () => {
  try {
    await brandStore.getBrandListFunc()
  } catch (e: any) {
    ElNotification({
      message: e,
      type: 'error',
    })
  }
})

const batchDelete = async () => {
  if (tableRef.value) {
    const selectedRows = tableRef.value.getSelectionRows();
    const ids = selectedRows.map((row: any) => row.ID);
    const res = await BatchDeleteBrand(ids)
    if (res.code === 200) {
      await brandStore.getBrandListFunc()
      ElNotification({
        message: '删除成功',
        type: 'success',
      })
    } else {
      ElNotification({
        message: res.msg,
        type: 'error',
      })
    }
  } else {
    console.warn('Table component not initialized');
  }
}

</script>

<template>
  <div>
    <el-container>
      <el-main>
        <el-form :model="brandStore.reqFrom" inline>
          <el-form-item label="品牌名称">
            <el-input v-model="brandStore.reqFrom.name" clearable />
          </el-form-item>
          <el-form-item label="品牌地区">
            <el-select v-model="brandStore.reqFrom.region" filterable style="width: 240px" :loading="requestRegion"
              @focus="getRegionFunc" clearable>
              <el-option v-for="item in brandStore.regionOptions" :key="item.name" :label="item.name"
                :value="item.name" />
            </el-select>
          </el-form-item>
          <el-form-item label="品牌类别">
            <el-select v-model="brandStore.reqFrom.category" filterable style="width: 240px" :loading="requestRegion"
              @focus="getCategoryFunc" clearable>
              <el-option v-for="item in brandStore.categoryOptions" :key="item.name" :label="item.name"
                :value="item.name" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="brandStore.reqFrom.status" placeholder="选择是否启用" style="width: 200px">
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="queryBrand">查询</el-button>
          </el-form-item>
        </el-form>
        <div class="action_button">
          <el-button type="primary" @click="brandStore.addBrand = true" v-if="loginStore.buttonPermissions.BrandCreate">
            新增品牌
          </el-button>
          <el-button type="primary" v-if="loginStore.buttonPermissions.BrandBatchDel"
            @click="batchDelete">批量删除</el-button>
        </div>
        <el-table :data="brandStore.brandList" table-layout="auto" ref="tableRef" border>
          <el-table-column type="selection" />
          <el-table-column prop="ID" label="ID" header-align="center" align="center"></el-table-column>
          <el-table-column prop="name" label="品牌名称" header-align="center" align="center"></el-table-column>
          <el-table-column prop="logo" label="品牌logo" header-align="center" align="center">
            <template #default="scope">
              <img :src="scope.row.logo" alt="" style="width: 50px;height: 50px;" />
            </template>
          </el-table-column>
          <el-table-column prop="description" label="品牌描述" header-align="center" align="center"></el-table-column>
          <el-table-column prop="region" label="品牌地区" header-align="center" align="center">
            <template #default="scope">
              <el-tag type="primary" size="large">
                {{
                  scope.row.region.name
                }}
              </el-tag>
            </template>

          </el-table-column>
          <el-table-column prop="category" label="品牌类别" header-align="center" align="center">
            <template #default="scope">
              <el-tag type="primary" size="large">
                {{
                  scope.row.category.name
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="启用状态" header-align="center" align="center">
            <template #default="scope">
              <el-tag type="success" size="large" v-if="scope.row.status === 1">启用</el-tag>
              <el-tag type="danger" size="large" v-else>禁用</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="sort" label="排序" header-align="center" align="center"></el-table-column>
          <el-table-column prop="CreatedAt" label="创建时间" header-align="center" align="center">
            <template #default="scope">
              {{
                scope.row.CreatedAt.replace('T', ' ').slice(0, 19)
              }}
            </template>

          </el-table-column>
          <el-table-column prop="UpdatedAt" label="更新时间" header-align="center" align="center">
            <template #default="scope">
              {{
                scope.row.UpdatedAt.replace('T', ' ').slice(0, 19)
              }}
            </template>
          </el-table-column>
          <el-table-column label="操作" header-align="center" align="center" min-width="110"
            v-if="loginStore.buttonPermissions.BrandEdit || loginStore.buttonPermissions.BrandDel">
            <template #default="scope">
              <el-button type="primary" :icon="Edit" circle v-if="loginStore.buttonPermissions.BrandEdit"
                @click="edit(scope.row)"></el-button>
              <el-button type="danger" :icon="Delete" circle v-if="loginStore.buttonPermissions.BrandDel"
                @click="del(scope.row)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-wrapper">
          <el-pagination v-model:current-page="brandStore.reqFrom.page" v-model:page-size="brandStore.reqFrom.pageSize"
            :page-sizes="brandStore.pageSize" :background="true" layout="total, sizes, prev, pager, next, jumper"
            :total="brandStore.total" @change="pagination" />
        </div>
      </el-main>
    </el-container>
    <AddBrand v-if="brandStore.addBrand"></AddBrand>
    <EditBrand v-if="brandStore.editBrand"></EditBrand>
  </div>
</template>

<style scoped lang="scss">
.action_button {
  margin-bottom: 10px;
}

.pagination-wrapper {
  display: flex; // 启用Flexbox
  justify-content: flex-end; // 子项靠右对齐
  margin-top: 20px; // 设置分页组件距离上边表格的距离
}
</style>